<template>
  <div class="sidebar-wrapper">
    <aside class="sidebar" :class="{ 'collapsed': isCollapsed }">
      <div class="sidebar-header">
        <el-input
          placeholder="搜索产业链"
          v-model="input4"
          v-show="!isCollapsed">
          <i slot="suffix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </div>

      <div class="sidebar-content" ref="sidebarContent">
        <el-collapse v-model="activeNames">
          <el-collapse-item name="2">
            <template #title>
              <div class="header-with-icon">
                <i class="el-icon-loading"></i>
                <span>生成中</span>
              </div>
            </template>
            <div class="category-contentqqq">
              <div v-for="(item, index) in filteredChainStatus" 
                 :key="index" 
                 class="category-itemqqqq" @click="handleClick(item)">
                
                  <h3 :title="item" style="text-align: center;margin-bottom: 5px;">
                  {{ isCollapsed ? item.substr(0, 2) : item }}
                  
                  </h3>
                  <el-progress :text-inside="true" :stroke-width="26" :percentage="taskProgress[item]"></el-progress>
            
                
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
        <el-collapse>
          <el-collapse-item name="3">
            <template #title>
              <div class="header-with-icon">
                <i class="el-icon-check"></i>
                <span>已完成</span>
              </div>
            </template>
            <div class="category-content">
              <a v-for="(item, index) in filteredItems" 
                 :key="index" 
                 :href="item.link" 
                 target="_blank" 
                 class="category-item">
                <div :title="item.text">
                  {{ isCollapsed ? item.text.substr(0, 2) : item.text }}
                </div>
              </a>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>

      <div class="sidebar-footer">
        <router-link v-if="!isUserLoggedIn" to="/login" class="login-link">
          <i class="el-icon-user"></i>
          <span v-if="!isCollapsed">用户登录</span>
        </router-link>
        <a v-else @click="handleLogout" class="login-link">
          <i class="el-icon-switch-button"></i>
          <span v-if="!isCollapsed">退出登录</span>
        </a>
      </div>
    </aside>
    <div class="collapse-btn" 
         @click="toggleCollapse"
         :data-tooltip="isCollapsed ? '展开侧边栏' : '收起侧边栏'">
      <i :class="isCollapsed ? 'el-icon-d-arrow-right' : 'el-icon-d-arrow-left'"></i>
    </div>
  </div>
</template>

<script>
import api from '@/api'

export default {
  name: 'Sidebar',
  data() {
    return {
      input4: '',
      isCollapsed: false,
      isExpanded: false,
      activeNames: ['1'], // 默认展开第一个面板
      items: [
        { text: '机器人', link: 'http://60.205.177.144:8094/#/ai/robot' },
        { text: '半导体', link: 'http://60.205.177.144:8094/#/ai/semiconductor' },
        { text: '汽车', link: 'http://60.205.177.144:8094/#/ai/car' },
        { text: '低空经济', link: 'http://60.205.177.144:8094/#/ai/lae' },
        { text: '电子商务', link: 'http://60.205.177.144:8094/#/ai/ec' },
        { text: '机械设备与零件', link: 'http://60.205.177.144:8094/#/ai/mep' },
        { text: '生物医药', link: 'http://60.205.177.144:8094/#/ai/biomedical' },
        { text: '生命健康', link: 'http://60.205.177.144:8094/#/ai/bigheal' },
        { text: '通信设备', link: 'http://60.205.177.144:8094/#/ai/icd' },
        { text: '电子器件', link: 'http://60.205.177.144:8094/#/ai/ed' },
        { text: '电子信息', link: 'http://60.205.177.144:8094/#/ai/ei' },
        { text: '大健康', link: 'http://60.205.177.144:8094/#/ai/bh' },
        { text: '工业母机', link: 'http://60.205.177.144:8094/#/ai/imm' },
        { text: '轨道交通设备', link: 'http://60.205.177.144:8094/#/ai/rte' },
        { text: '工业软件', link: 'http://60.205.177.144:8094/#/ai/is' },
        { text: '装备制造', link: 'http://60.205.177.144:8094/#/ai/manufacture' },
        { text: '集成电路', link: 'http://60.205.177.144:8094/#/ai/ic' },
        { text: '能源保护', link: 'http://60.205.177.144:8094/#/ai/eep' }
      ],
      chainsstatus: [],
      springnumber: 0,
      taskProgress: {} // 用于存储每个任务的进度
    }
  },
  mounted() {
    // 添加事件监听
    this.$root.$on('message-processing', () => {
      this.isCollapsed = true;
    });
    
    // 添加监听更新事件
    this.$root.$on('update-chain-status', () => {
      this.updateChainStatus();
    });
    
    // 添加监听新增产业链状态事件
    this.$root.$on('add-new-chain-status', (newStatus) => {
      this.addNewChainStatus(newStatus);
    });
    
    // 添加监听任务进度更新事件
    this.$root.$on('update-task-progress', (progressInfo) => {
      this.updateTaskProgress(progressInfo.taskName, progressInfo.progress);
    });
    
  //   // 初始加载数据
    this.updateChainStatus();
  //   this.$root.$on('update-progress', (progressInfo) => {
  //   // progressInfo 包含了所有进度信息
  //   console.log('收到进度更新：', progressInfo);
  //   for (let i = 0; i < this.chainsstatus.length; i++) {
  //   if (this.chainsstatus[i] === progressInfo.taskName) {
  //     console.log(this.chainsstatus[i], "this.chainsstatus[i]")
  //     // 如果匹配成功，更新对应的 springnumber
  //     this.springnumber = progressInfo.progress;
  //     break; // 找到匹配后退出循环
  //   }
  // }
 
    // 在这里处理进度信息
  // });
  },
  beforeDestroy() {
    // 移除事件监听
    this.$root.$off('message-processing');
    this.$root.$off('update-chain-status');
    this.$root.$off('add-new-chain-status');
    this.$root.$off('update-task-progress');
  },
  computed: {
    filteredItems() {
      if (!this.input4) {
        return this.items;
      }
      return this.items.filter(item => 
        item.text.toLowerCase().includes(this.input4.toLowerCase())
      );
    },
    filteredChainStatus() {
      if (!this.input4) {
        return this.chainsstatus;
      }
      return this.chainsstatus.filter(item => 
        item.toLowerCase().includes(this.input4.toLowerCase())
      );
    },
    visibleItems() {
      return this.filteredItems.slice(0, 5);
    },
    expandableItems() {
      return this.filteredItems.slice(5);
    },
    isUserLoggedIn() {
      return localStorage.getItem('isLoggedIn') === 'true';
    }
  },
  created() {
    this.$root.$on('update-progress', (progressInfo) => {
      console.log('收到进度更新：', progressInfo);

      // 更新对应任务的进度
      if (this.chainsstatus.includes(progressInfo.taskName)) {
        this.$set(this.taskProgress, progressInfo.taskName, progressInfo.progress);
      }
    });
},
  methods: {
    updateChainStatus() {
    api.user.chainsstatus().then(res => {
      if (res && res.data) {
        const newChainsStatus = res.data.in_progress;
        const oldChainStatus = [...this.chainsstatus];

        // 如果是首次加载（oldChainStatus为空），则所有任务设为100%
        // 否则，只有新加入的任务设为0%，已存在的任务保持100%
        newChainsStatus.forEach(task => {
          if (oldChainStatus.length === 0 || oldChainStatus.includes(task)) {
            this.$set(this.taskProgress, task, 100);
          } else {
            this.$set(this.taskProgress, task, 0);
          }
        });

        // 更新 chainsstatus
        this.chainsstatus = newChainsStatus;
      }
    }).catch(err => {
      console.error('获取产业链状态失败:', err);
    });
  },
  // 新增方法：手动添加产业链状态
  addNewChainStatus(newStatus) {
    if (!newStatus || typeof newStatus !== 'string') {
      console.error('无效的产业链状态');
      return;
    }
    
    // 检查是否已存在该状态
    if (!this.chainsstatus.includes(newStatus)) {
      // 添加新状态到数组开头
      this.chainsstatus.unshift(newStatus);
      
      // 设置初始进度为0
      this.$set(this.taskProgress, newStatus, 0);
      
      console.log(`已添加新的产业链状态: ${newStatus}`);
    } else {
      console.log(`产业链状态已存在: ${newStatus}`);
    }
  },
  // 更新进度
  updateTaskProgress(taskName, progressValue) {
    // 检查任务是否存在
    if (this.chainsstatus.includes(taskName)) {
      // 更新进度
      this.$set(this.taskProgress, taskName, progressValue);
      console.log(`已更新任务"${taskName}"的进度为${progressValue}%`);
    } else {
      console.error(`任务"${taskName}"不存在，无法更新进度`);
    }
  },
    handleClick(item) {
      let params = {
        industry_name: item
      }
      api.user.getdbstructure(params).then(res=>{
        console.log(item, "res");
        this.$emit('showMindView', res.data,item);
      })
    },
    toggleCollapse() {
      this.isCollapsed = !this.isCollapsed;
    },
    toggleExpand() {
      this.isExpanded = !this.isExpanded;
    },
    handleLogout() {
      // 清除登录状态
      localStorage.removeItem('isLoggedIn');
      localStorage.removeItem('username');
      
      // 跳转到登录页面
      this.$router.push('/login');
    }
  }
}
</script>

<style  scoped>
.sidebar-wrapper {
  position: relative;
  height: 100vh;
  display: flex;
}

.sidebar {
  width: 300px;
  height: 100vh;
  background-color: #f3f5fc;
  border-right: 1px solid #e5e5e5;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
  transition: width 0.3s ease;
}

.sidebar.collapsed {
  width: 100px;
}

.collapse-btn {
  position: fixed;
  left: 300px;  /* 与侧边栏宽度对齐 */
  top: 50%;
  transform: translateY(-50%);
  width: 20px;   /* 减小宽度 */
  height: 40px;
  background-color: #409EFF;
  border: 2px solid #fff;
  border-radius: 0 20px 20px 0;  /* 只设置右侧为圆角 */
  border-left: none;  /* 移除左边框 */
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 1;
  box-shadow: 2px 0 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.sidebar.collapsed + .collapse-btn {
  left: 100px;  /* 收起时的位置 */
}

.collapse-btn:hover {
  background-color: #66b1ff;
  transform: translateY(-50%) scale(1.05);
}

.collapse-btn i {
  color: #fff;
  font-size: 14px;  /* 稍微调小图标 */
  transition: transform 0.3s ease;
  margin-left: -2px;  /* 微调图标位置 */
}

.collapsed .collapse-btn i {
  transform: rotate(0deg);
}

/* 修改提示文字的位置 */
.collapse-btn::after {
  content: attr(data-tooltip);
  position: absolute;
  left: 25px;  /* 调整提示文字位置 */
  background: rgba(0, 0, 0, 0.75);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s ease;
}

.collapse-btn:hover::after {
  opacity: 1;
  visibility: visible;
}

/* 添加动画效果 */
@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(64, 158, 255, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0);
  }
}

.collapse-btn:not(:hover) {
  animation: pulse 2s infinite;
}

.sidebar-header {
  padding: 14px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  /* border-bottom: 1px solid #f0f0f0; */
}

.logo {
  display: flex;
  align-items: center;
  gap: 8px;
 
}

.new-chat-btn {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  border: 1px solid #fff;
  background: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #333;
}

.sidebar-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px 0;
  position: relative;
}

.visible-content,
.expandable-content {
  padding: 0 16px;
}

.visible-content div,
.expandable-content div {
  width: 45%;
  height: 101px;
  background-image: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  float: left;
  margin: 5px;
  text-align: center;
  color: #fff;
  border-radius: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.expandable-content {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.3s ease;
}

.expandable-content.expanded {
  max-height: 1000px;
}

.expand-button {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  margin-top: 10px;
  cursor: pointer;
  color: #666;
  transition: all 0.3s ease;
}

.expand-button:hover {
  color: #409EFF;
}

.expand-button i {
  margin-right: 5px;
}

/* 收起状态的样式 */
.collapsed .visible-content div,
.collapsed .expandable-content div {
  width: 80%;
  height: 60px;
  margin: 5px auto;
  float: none;
}

.section-header {
  padding: 6px 16px;
  font-size: 0.75rem;
  color: #666;
  margin-top: 8px;
}

.chat-history {
  margin-bottom: 8px;
}

.chat-item {
  padding: 8px 16px;
  cursor: pointer;
  font-size: 0.875rem;
  color: #333;
  border-radius: 0;
  margin: 2px 0;
}

.chat-item:hover {
  background-color: #f5f5f5;
}

.chat-item.active {
  background-color: #f0f7ff;
  color: #1E88E5;
}

.sidebar-footer {
  padding: 14px;
  border-top: 1px solid #f0f0f0;
}

.login-link {
  display: flex;
  align-items: center;
  gap: 8px;
  text-decoration: none;
  color: #409eff;
  padding: 10px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.login-link:hover {
  background-color: #ecf5ff;
}

.upgrade-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #f5f5f5;
  border-radius: 6px;
  cursor: pointer;
  color: #333;
  font-size: 0.875rem;
}

.hint-text {
  font-size: 0.75rem;
  color: #999;
  margin-top: 4px;
}

.category-content {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 10px;
}

.category-item {
  text-decoration: none;
  width: calc(50% - 5px);
}

.header-with-icon {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
  flex: 1;
}

.header-with-icon span {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.header-with-icon i {
  font-size: 18px;
  flex-shrink: 0;
}

.collapsed .header-with-icon span {
  display: none;
}

.collapsed .header-with-icon i {
  font-size: 20px;
  margin: 0 auto;
}

.header-with-icon i.el-icon-hot-water {
  color: #ff4d4f;
}

.header-with-icon i.el-icon-loading {
  color: #1a73e8;
}

.header-with-icon i.el-icon-check {
  color: #52c41a;
}

.category-item div {
  background: #f3f5fc;
  color: black;
  border-radius: 15px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  padding: 0 12px;
  text-align: center;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.collapsed .category-item div {
  height: 50px;
  font-size: 14px;
  padding: 0 8px;
}

/* Element UI Collapse 组件自定义样式 */
.el-collapse {
  border: none;
}

::v-deep .el-collapse-item__header {
  height: 60px;
  line-height: 60px;
  background-color: #f3f5fc;
  color: #303133;
  cursor: pointer;
  border-bottom: 1px solid #EBEEF5;
  font-size: 17px;
  font-weight: 600;
  transition: all 0.3s ease;
  outline: 0;
  align-items: center;
  padding: 0 20px;
  display: flex;
}

.collapsed ::v-deep .el-collapse-item__header {
  padding: 0 10px;
  justify-content: center;
}

.collapsed ::v-deep .el-collapse-item__arrow {
  display: none;
}

::v-deep .el-collapse-item__header:after {
  margin-left: 8px;
  font-family: element-icons !important;
  font-size: 20px;
}

::v-deep .el-collapse-item__header[aria-controls="el-collapse-content-1"]:after {
  content: "\e79c";
  color: #ff4d4f;
}

::v-deep .el-collapse-item__header[aria-controls="el-collapse-content-2"]:after {
  content: "\e6c9";
  color: #1a73e8;
}

::v-deep .el-collapse-item__header[aria-controls="el-collapse-content-3"]:after {
  content: "\e6da";
  color: #52c41a;
}

.el-collapse-item__content {
  padding: 0;
}

.el-collapse-item__wrap {
  border: none;
}
.category-contentqqq{
 width: 100%;
    height: 100%;
    display: flex
;
    flex-wrap: wrap;
}
   
.category-itemqqqq{
width: 46%;
    height: 99px;
    margin: 5px;
    background: #f3f5fc;
    /* background-image: linear-gradient(to top, #dad4ec 0%, #dad4ec 1%, #f3e7e9 100%); */
    display: flex
;
    flex-direction: column;
    justify-content: center;
        border-radius: 10px;
}
/* ::v-deep(.el-progress-bar__inner) {
  background:;
} */

/* 自定义进度条样式 */
::v-deep .el-progress-bar__inner {
  background-image: linear-gradient(to right, #4facfe 0%, #00f2fe 100%);
  transition: all 0.3s ease;
}

::v-deep .el-progress-bar__outer {
  background-color: #ebeef5;
  border-radius: 15px;
}

::v-deep .el-progress__text {
  color: #606266;
  font-size: 12px !important;
  margin-left: 5px;
}

.category-itemqqqq:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  transition: all 0.3s ease;
}
</style> 